/*
 * Created on Mar 5, 2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.sales.ContactPerson;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.forms.AddNewContactPersonForm;
import com.scalar.chiptrack.users.User;

/**
 * @author Administrator
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class AddNewContactPersonAction extends ChipTrackAction
{

	private static final String ACTION_NAME = "/addNewContactPerson.do" ;

    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {

        HttpSession session = request.getSession();
   	  	User user           = ( User ) session.getAttribute( SessionKeys.USER_KEY );

		if( user == null )
		{
			session.setAttribute( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString() );
			return ( mapping.findForward ( "login" ) );
		}


		HashMap errors = new HashMap();
		request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);

		HashMap info = new HashMap();
		request.setAttribute (SessionKeys.INFO_MESSAGES, info);


		AddNewContactPersonForm contactpersonform = ( AddNewContactPersonForm ) form;
        String action               = request.getParameter( "action" );
        int customerId              = Integer.parseInt( request.getParameter( "customerId" ) );
		String contactPersonValue   = request.getParameter( "value" );

		request.setAttribute( "contactPersons", CustomerDAO.getAllContactPersonsWithActions( customerId , contactPersonValue ) );

		if( "disable".equalsIgnoreCase( request.getParameter( "contactPersonstatus" ) ) == true )
		{
			String contactPersonToDelete = request.getParameter( "contactPerson" );
			if ( ( contactPersonToDelete != null ) && ( contactPersonToDelete.trim().length() != 0 ) )
			{
				try
				{
					CustomerDAO.deleteContactPerson( contactPersonToDelete , customerId, contactPersonValue );
					info.put ( contactPersonToDelete + " has been disabled", null  );
				}
				catch( ScalarException se )
				{
					se.printStackTrace ();
					errors.put ("Internal Server Error", "Could not delete \"" + contactPersonToDelete + "\"");
				}
			}
		}
		else if ( "activate".equalsIgnoreCase(request.getParameter( "contactPersonstatus" ) ) == true )
		{
            String contactPersonToActivate = request.getParameter( "contactPerson" );
			if ( ( contactPersonToActivate != null ) && ( contactPersonToActivate.trim().length() != 0 ) )
			{
			    try
				{
				    CustomerDAO.activateContactPerson ( contactPersonToActivate , customerId , contactPersonValue );
				    info.put( contactPersonToActivate + " has been activated", null );
				}
				catch( ScalarException se )
				{
				    se.printStackTrace ();
				    errors.put ("Internal Server Error", "Could not activate \"" + contactPersonToActivate + "\"");
				}
  			}
		}
        String contactperson;
        if( "insertContactPerson".equalsIgnoreCase( action ) )
		{
			contactperson = request.getParameter( "newContactPerson" );
			boolean success             = false;
			boolean temp                = false;
            int allcontactpersonsSize   = 0;
            ContactPerson contactPerson = null;

            if( ( contactperson == null ) || ( contactperson.trim().length() == 0 ) )
            {
				errors.put ( ERROR_CUSTOMER_INVALID_CONTACT_PERSON, null );
				return( mapping.findForward ( "success" ) );
			}
            ArrayList allcontactpersons = CustomerDAO.getAllContactPersonsWithActions( customerId, contactPersonValue );
            allcontactpersonsSize = allcontactpersons.size();


			for( int j = 0; j < allcontactpersonsSize; j++ )
			{
				contactPerson = ( ContactPerson ) allcontactpersons.get( j );
				String contactpersonname = contactPerson.getContactPerson();
				if( ( contactperson != null ) && ( contactpersonname != null ) )
				{
					if( contactperson.trim().equalsIgnoreCase( contactpersonname ) )
					{
						temp= true;
						break;
					}
				}
			}//for end

			if( temp == true )
            {
				errors.put ( contactperson + " " + ERROR_CUSTOMER_REP_ALREADY_EXISTS, null );
				return ( mapping.findForward ( "success" ) );
			}

			try
            {
                CustomerDAO.insertContactPerson( null, customerId , contactperson,
													contactpersonform.getPhoneNumber(),
													contactpersonform.getCellNumber(),
													contactpersonform.getFaxNumber(),
													contactpersonform.getEmail(),
                                                    contactpersonform.getSalesAckMail(),
                                                    contactpersonform.getShipAlerts() ,
                                                    contactpersonform.getProformaInvoice() ,
                                                    contactpersonform.getPackingSlip() ,
                                                    contactpersonform.getCommerInvoice() ,
													contactpersonform.getAddress(),
													contactPersonValue, contactpersonform.isQuoteAckMail(), contactpersonform.isRmaAckMail() );
				info.put ( INFO_CONTACT_PERSON_SUCCESSFULLY_STORED, null );
				success = true;
			}
			catch (ScalarException se)
            {
				errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
				se.printStackTrace();
			}
            contactpersonform.setNewContactPerson("");
			contactpersonform.setPhoneNumber("");
			contactpersonform.setCellNumber("");
			contactpersonform.setFaxNumber("");
			contactpersonform.setEmail("");
            contactpersonform.setAddress( "" );
            contactpersonform.setSalesAckMail( false );
            contactpersonform.setShipAlerts( false );
            contactpersonform.setProformaInvoice( false );
            contactpersonform.setPackingSlip( false );
            contactpersonform.setCommerInvoice( false );
            contactpersonform.setQuoteAckMail( false );
            contactpersonform.setRmaAckMail( false );
        }
        if( "saveEditContactPerson".equalsIgnoreCase( action ) )
		{
            contactperson = request.getParameter("newContactPerson");
			boolean success = false;
			boolean temp    = false;

            String oldContactPerson = ( String )session.getAttribute( "oldContactPerson" );

            if( ( contactperson == null ) || ( contactperson.trim().length() == 0 ) )
            {
				errors.put ( ERROR_CUSTOMER_INVALID_CONTACT_PERSON, null );
				return ( mapping.findForward ( "success" ) );
			}
            if( CustomerDAO.isContactPersonExists( contactperson, contactPersonValue, customerId, oldContactPerson ) )
            {
                errors.put ( "ContactPerson", "Contact Person Already Exists with Name " + contactperson ) ;
                contactpersonform.setNewContactPerson( oldContactPerson );
                contactpersonform.setAction( "editContactPerson" );
				return ( mapping.findForward( "success" ) );
            }
            try
            {

				CustomerDAO.changeContactPersonDetails( null, customerId , contactperson,
													    contactpersonform.getPhoneNumber(),
													    contactpersonform.getCellNumber(),
													    contactpersonform.getFaxNumber(),
													    contactpersonform.getEmail(),
                                                        contactpersonform.getSalesAckMail(),
                                                        contactpersonform.getShipAlerts() ,
                                                        contactpersonform.getProformaInvoice() ,
                                                        contactpersonform.getPackingSlip() ,
                                                        contactpersonform.getCommerInvoice() ,
													    contactpersonform.getAddress(),
													    contactPersonValue,
                                                        oldContactPerson, contactpersonform.isQuoteAckMail(), contactpersonform.isRmaAckMail() );
				info.put ( INFO_CONTACT_PERSON_SUCCESSFULLY_STORED, null );
				success = true;
			}
			catch (ScalarException se)
            {
				errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
				se.printStackTrace();
			}
            contactpersonform.setNewContactPerson("");
			contactpersonform.setPhoneNumber("");
			contactpersonform.setCellNumber("");
			contactpersonform.setFaxNumber("");
			contactpersonform.setEmail("");
            contactpersonform.setAddress( "" );
            contactpersonform.setSalesAckMail( false );
            contactpersonform.setShipAlerts( false );
            contactpersonform.setProformaInvoice( false );
            contactpersonform.setPackingSlip( false );
            contactpersonform.setCommerInvoice( false );
            contactpersonform.setQuoteAckMail( false );
            contactpersonform.setRmaAckMail( false);
        }
        if( "editContactPerson".equalsIgnoreCase( action ) )
        {
            String contactPersontoEdit = request.getParameter("contactPerson");
            session.setAttribute( "oldContactPerson", contactPersontoEdit );
            if( ( contactPersontoEdit != null ) && ( contactPersontoEdit.trim().length() != 0 ) )
			{
				try
				{
                    ContactPerson contactPerson = CustomerDAO.editContactPerson( contactPersontoEdit , customerId ,contactPersonValue );
                    PropertyUtils.copyProperties ( contactpersonform, contactPerson );
                    contactpersonform.setNewContactPerson( contactPerson.getContactPerson() );
				}
				catch (ScalarException se)
				{
					se.printStackTrace ();
					errors.put ( "Internal Server Error", "Could not get Data to Edit \"" + contactPersontoEdit + "\"" );
				}
			}

        }
		request.setAttribute( "contactPersons", CustomerDAO.getAllContactPersonsWithActions( customerId, contactPersonValue ) );
        request.setAttribute( "addNewContactPersonForm", contactpersonform );

        return (mapping.findForward ("success"));
	}



}
